<template>
    <div>
        <el-button size="small" type="primary" round @click="handleOpenAddDialog()">添加用户</el-button>
        <el-table :data="userList" style="width: 100%">
            <el-table-column prop="username" label="用户名" width="180" />
            <el-table-column prop="role.roleName" label="角色类型" width="180" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleOpenEditDialog(scope.row)" size="small" type="primary" round
                        :disabled="scope.row.default">编辑</el-button>
                    <el-popconfirm title="确定要删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button size="small" type="danger" round :disabled="scope.row.default">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- @opened="handleDialogOpened" :visible.sync="dialogVisible" -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="userForm" label-width="100px" :label-position="'right'" ref="userFormRef">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" type="password" show-password />
                </el-form-item>
                <el-form-item label="角色类型" prop="role">
                    <el-select v-model="userForm.role" placeholder="请选择角色类型">
                        <el-option v-for="item in roleList" :key="item._id" :label="item.roleName" :value="item._id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddOrUpdate">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
const userList = ref([])    // 角色列表
const roleList = ref([])    // 权限列表
const title = ref('')
const userFormRef = ref(null)
onMounted(async () => {
    await Promise.all([getList(), getRoleList()])

    // 调用接口获取角色列表数据
    // getList()

    // getRoleList()
})

const getList = async () => {
    var res = await axios.get('/adminapi/users')
    userList.value = res.data
}

const getRoleList = async () => {
    var res = await axios.get('/adminapi/roles')
    roleList.value = res.data
}

// 控制对话框显示隐藏
const dialogVisible = ref(false)
const userForm = reactive({
    username: '',
    password: '',
    role: ''
})


const handleOpenAddDialog = () => {
    title.value = '添加用户'
    dialogVisible.value = true
    nextTick(() => {
        userFormRef.value.resetFields()
    })
    // 表单项都赋为空
    // userForm.username = ''
    // userForm.password = ''
    // userForm.role = ''
}

// const handleDialogOpened = () => {
//     userFormRef.value.resetFields()
// }

const handleAddOrUpdate = () => {
    if (title.value === '添加用户') {
        handleAdd()
    } else {
        handleUpdate()
    }
}

const handleAdd = async () => {
    dialogVisible.value = false
    addUser()
}

const addUser = async () => {
    // console.log(userForm)
    var res = await axios.post('/adminapi/users', userForm)

    if (res.statusText === 'OK') {
        ElMessage({
            message: '更新成功',
            type: 'success'
        })
        await getList()
        // 如果需要保证管理员更新权限名称后后，就能立即看到左侧菜单栏的变更，可以通过刷新界面这种简单的方式实现
        // location.reload()
    } else {
        ElMessage({
            message: '更新失败',
            type: 'error'
        })
    }
}

// 保存当前更新的item项的_id
let curItemId

const handleOpenEditDialog = (row) => {
    title.value = '编辑用户'
    dialogVisible.value = true
    nextTick(() => {
        userForm.username = row.username
        userForm.password = row.password
        userForm.role = row.role._id
        curItemId = row._id
    })
}

const handleUpdate = () => {
    dialogVisible.value = false
    updateUser()
}

const updateUser = async () => {
    console.log(curItemId)

    var res = await axios.put(`/adminapi/users/${curItemId}`, userForm)
    if (res.statusText === 'OK') {
        ElMessage({
            message: '更新成功',
            type: 'success'
        })
        await getList()
        // 如果需要保证管理员更新权限名称后后，就能立即看到左侧菜单栏的变更，可以通过刷新界面这种简单的方式实现
        // location.reload()
    } else {
        ElMessage({
            message: '更新失败',
            type: 'error'
        })
    }
}

const handleDelete = async (row) => {
    axios.delete('/adminapi/users', {
        data: {
            id: row._id
        }
    })
    // location.reload()
    await getList()
}
</script>